document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const messageDiv = document.getElementById('message');

    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();

        const phone = document.getElementById('phone').value;
        let password = document.getElementById('password').value;

        // 简单的前端验证
        if (!phone || !password) {
            showMessage('请输入手机号和密码', 'error');
            return;
        }

        // 对密码进行MD5加密
        password = CryptoJS.MD5(password).toString();

        // 发送登录请求
        fetch('/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `phone=${encodeURIComponent(phone)}&password=${encodeURIComponent(password)}`
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Received data:', data);
                if (data.status === 'success') {
                    showMessage('登录成功，正在跳转...', 'success');
                    // 存储JWT token到localStorage
                    localStorage.setItem('Authorization', data.token);
                    setTimeout(() => {
                        window.location.href = '/home';
                    }, 1000);
                } else {
                    showMessage('手机号或密码错误', 'error');
                }
            })
            .catch(error => {
                showMessage('登录请求失败，请重试', 'error');
                console.error('Error:', error);
            });
    });

    function showMessage(text, type) {
        messageDiv.textContent = text;
        messageDiv.className = 'message ' + type;
    }
});
